import axios from "axios";
import store from "@/store";
import { Message } from "element-ui";
const instance = axios.create({
  baseURL: "/api",
  timeout: 5000,
  // headers: {'X-Custom-Header': 'foobar'}
});

// 添加请求拦截器
instance.interceptors.request.use(
  function (config) {
    //请求头添加token
    if (store.state.user.userInfo) {
      config.headers.Authorization = store.state.user.userInfo.token;
    }
    return config;
  },
  function (err) {
    return Promise.reject(err);
  }
);

// 添加响应拦截器
instance.interceptors.response.use(
  function (response) {
    //直接获取返回的data
    return response.data;
  },
  function (err) {
    if (err && err.response) {
      switch (err.response.status) {
        case 400:
          err.message = "请求出错";
          break;
        case 401:
          Message.warning({
            message: "授权失败，请重新登录",
          });
          store.commit("LOGIN OUT");
          setTimeout(() => {
            window.location.reload();
          }, 1000);
          return;
        case 403:
          err.message = "拒绝访问";
          break;
        case 404:
          err.message = "请求错误，未找到该资";
          break;
        case 500:
          err.message = "服务器端出错";
          break;
      }
    } else {
      err.message = "连接服务器失败";
    }
    Message.error({ message: err.message });
    return Promise.reject(err);
  }
);
export default instance;
